package handler

import (
	"html/template"
	"net/http"

	"chainmaker.org/chainmaker/smarteditor/common"
	"chainmaker.org/chainmaker/smarteditor/conf"
	"chainmaker.org/chainmaker/smarteditor/container"
	"chainmaker.org/chainmaker/smarteditor/i18n"
	"chainmaker.org/chainmaker/smarteditor/session"
	"github.com/88250/gulu"
	"github.com/gorilla/sessions"
)

// indexHandler handles request of Wide index.
func indexHandler2(w http.ResponseWriter, r *http.Request) {
	uid, err := session.GetUidFromSession(r)
	if err != nil {
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	httpSession, _ := session.HTTPSession.Get(r, session.CookieName)
	sessionId := httpSession.Values[common.SessionIdName].(string)

	if !container.SC.SessionManager.Exists(sessionId) {
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		log.Warnf("[indexHandler] check session, session not exists. session id: %s", sessionId)
		return
	}

	err = updateSession(w, r, httpSession)
	if err != nil {
		log.Errorf("[indexHandler] update session failed. err: %s", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	user := conf.GetUser(uid)
	if nil == user {
		log.Errorf("[indexHandler] user not found, redirect to login page.")
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	temp, err := template.ParseFiles("views/index.html")
	if nil != err {
		log.Errorf("[indexHandler] parse templete file failed. uid:%s, err:%s", uid, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err = temp.Execute(w, getIndexPageModule(user, sessionId)); err != nil {
		log.Errorf("[indexHandler] render templete file failed. uid:%s, err:%s", uid, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

// indexHandler handles request of Wide index.
func indexHandler(w http.ResponseWriter, r *http.Request) {
	uid, err := session.GetUidFromSession(r)
	if err != nil {
		log.Debugf("indexHandler GetUidFromSession error %s", err.Error())
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	httpSession, _ := session.HTTPSession.Get(r, session.CookieName)
	log.Debugf("indexHandler got httpSession %+v ", httpSession.Values)
	sessionId := httpSession.Values[common.SessionIdName].(string)

	if !container.SC.SessionManager.Exists(sessionId) {
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		log.Warnf("[indexHandler] check session, session not exists. session id: %s", sessionId)
		return
	}

	err = updateSession(w, r, httpSession)
	if err != nil {
		log.Errorf("[indexHandler] update session failed. err: %s", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	user := conf.GetUser(uid)
	if nil == user {
		log.Errorf("[indexHandler] user not found, redirect to login page.")
		//http.Redirect(w, r, common.LoginPath, http.StatusFound)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	gulu.Ret.RetJSON(w, r, getIndexPageModule(user, sessionId))

}

func updateSession(w http.ResponseWriter, r *http.Request, session *sessions.Session) error {
	session.Options.MaxAge = conf.Wide.HTTPSessionMaxAge
	return session.Save(r, w)
}

func getIndexPageModule(user *conf.User, sessionId string) map[string]interface{} {
	return map[string]interface{}{
		//"conf":                 conf.Wide,
		"i18n":                 i18n.GetAll(user.Locale),
		"locale":               user.Locale,
		"uid":                  user.ID,
		"sid":                  session.WideSessions.GenId(),
		"editorTheme":          user.Editor.Theme,
		"latestSessionContent": user.LatestSessionContent,
		"pathSeparator":        conf.PathSeparator,
		"editorTabSize":        user.Editor.TabSize,
		"keymap":               user.Keymap,
		"autocomplete":         conf.Wide.Autocomplete,
		//"codeMirrorVer":        conf.CodeMirrorVer,
		"user": user,
		//"editorThemes": conf.GetEditorThemes(),
		//"themes":               conf.GetThemes(),
		//"fontSizes":            []string{"12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px"},
		//"lineHeights":          []string{"14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px"},
	}
}
